/*
 * jQuery CTree Plugin
 * version v1.0 2010-07-26
 * Editor: collonn
 * Email: collonn@126.com
 */

(function($) {
	
	jQuery.fn.ctree = function(params){
		var $this = $(this);
		
		defaults = {
			loadingText:'loading',
			url:''
		};
		
		jQuery.extend(defaults,params);
		
		if(defaults.url == ''){
			return;
		}
		
		jQuery.fn.ctree.getSubTree($this, defaults.url, true);
	};
	
	jQuery.fn.ctree.getSubTree = function($source, url, isRoot){
		if($source.find('ul').length > 0){
			return;
		}
		
		var param = null;
		if(isRoot){
			param = "1";
		}else{
			param = $source.attr('id');
		}
		
		$.ajax({
			url:url,
			data:'root=' + param,
			dataType:'json',
			beforeSend:function(){
				
			},
			success:function(rs){
				if(rs == null)return;
				var ht = '';
				
				if(!isRoot)ht += '<ul>';
				for(var i = 0; i < rs.length; i++){
					ht += '<li id="' + rs[i].id + '">' + rs[i].text + '</li>';
				}
				if(!isRoot)ht += '</ul>';
				
				$source.append(ht).find('li').click(function(e){
					e.stopPropagation();
					jQuery.fn.ctree.getSubTree($(this), url, false);
				});
			},
			complete:function(){
				
			}
		});
	}
	
})(jQuery);